#!/usr/bin/python

import getopt,sys,os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage

def usage():
    print "Usage: mailhtml [-s subject] [-c cc-addr] [-b bcc-addr] ..."
    print "                [-f from-addr] to-addr"
    print "       mailhtml [-a non-html-alt-text] [-t non-html-input-file]"
    print "Usage: mailhtml [-o html-message]"



def main():

    strFrom = None
    strTo = None
    strSubject = None
    strCarbon = None
    strBlind = None
    strAltText = None
    strAltFile = None
    strHTMLFile = None

    try:
        opts,args = getopt.getopt(sys.argv[1:], "o:s:c:b:a:t:f:h", ["help", "input=", "server=","threads=","header="])
    except getopt.GetoptError:
        usage()
        sys.exit(2)

    for o, a in opts:
        if o in ("-h","--help"):
            usage()
            sys.exit()
        if o in ("-s"):
            strSubject = a
        if o in ("-c"):
            strCarbon = a
        if o in ("-b"):
            strBlind = a
        if o in ("-f"):
            strFrom = a
        if o in ("-a"):
            strAltText = a
        if o in ("-t"):
            strAltFile = a
        if o in ("-o"):
            strHTMLFile = a

    for a in args:
        strTo = a

    if strTo == None:
        usage()
        sys.exit()

    if strFrom == None:
        strFrom = os.environ['LOGNAME']

    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'] = strSubject
    msgRoot['From'] = strFrom
    msgRoot['To'] = strTo
    msgRoot.preamble = 'This is a multi-part message in MIME format.'

    msgAlternative = MIMEMultipart('alternative')
    msgRoot.attach(msgAlternative)
        
    if strAltText != None:
        msgText = MIMEText(strAltText)
        msgAlternative.attach(msgText)

    elif strAltFile != None:
        Text = ''
        file = open(strAltFile,"rb")
        for row in file :
            Text += row
        msgText = MIMEText(Text)
        msgAlternative.attach(msgText)
        
    if strHTMLFile == None :
        Text = ''
        for row in sys.stdin:
            Text += row
    else:
        Text = ''
        file = open(strHTMLFile,"rb")
        for row in file :
            Text += row

    msgText = MIMEText(Text,'html')
    msgAlternative.attach(msgText)

    import smtplib
    smtp = smtplib.SMTP()
    smtp.connect('localhost')
    smtp.sendmail(strFrom, strTo, msgRoot.as_string())
    smtp.quit()

if __name__ == "__main__":
    main()
